﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Avalon.Core.Data
{
    internal class ModelManipulation
    {
        internal static object Convert(Type targetType, object source)
        {
            var result = typeof(Mapper).GetMethod("Map", new Type[] { typeof(object) }).MakeGenericMethod(targetType).Invoke(null, new object[] { source });
            return result;
        }

        internal static void AddToChildCollection(object parent, object child, string collectionName = null)
        {
            Type collectionType = typeof(IEnumerable<>).MakeGenericType(child.GetType());
            PropertyInfo pInfo = parent.GetType().GetProperties().FirstOrDefault(p => collectionType.IsAssignableFrom(p.PropertyType));
            var property = pInfo.GetValue(parent);
            if (property == null)
            {
                if (pInfo.PropertyType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(pInfo.PropertyType.GetGenericTypeDefinition()))
                {
                    property = (IEnumerable<IEntity>)Activator.CreateInstance(typeof(List<>).MakeGenericType(pInfo.PropertyType.GetGenericArguments()[0]));
                }
                else
                {
                    property = Activator.CreateInstance(pInfo.PropertyType);
                }
                pInfo.SetValue(parent, property);
            }
            property.GetType().GetMethod("Add").Invoke(property, new object[] { child });
        }
    }
}
